// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init()

const db = cloud.database();
// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  try {
    var log = 0;
    var word_id = 0;
    var result = new Array();
    var array = new Array(); //存word_id
    var map = new Map(); //key：word_id value：背错次数
    //通过JS的方法获取当前年月日
    var date = new Date();
    date = new Date(date.getTime() + 8 * 60 * 60 * 1000);
    //获取年份  
    const Y = date.getFullYear();
    //获取月份  
    const M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1);
    //获取当日日期 
    const D = date.getDate() < 10 ? '0' + date.getDate() : date.getDate();

    let first = await db.collection('location').where({
      user_id: wxContext.OPENID,
    }).count();

    if (first.total == 0) { //第一次打开背单词界面
      word_id = 0;
    } else { //不是第一次打开

      let today = await db.collection('location').where({
        user_id: wxContext.OPENID,
        time: {
          year: Y,
          month: M,
          day: D,
        }
      }).get();

      if (today.data[0] == null) { //today.data[0]==null 上次背单词不是今天
        const yes = await cloud.callFunction({
          // 要调用的云函数名称
          name: 'last',
          // 传递给云函数的参数
          data: {
            openid: wxContext.OPENID,
          }
        });
        word_id = yes.result.word_id;
      } else { //上次背单词是今天
        //上次背单词是今天，则word_id为今天的word_id
        word_id = today.data[0].word_id;
      }
    }

    if (word_id == 0) { //从来没背过单词
      log = 0;
      return {
        _log: log,
        words: result,
      }
    } else if (word_id <= event.num) { //背的单词数小于设定值
      log = 1;
      for (let i = 1; i <= word_id; i++) {
        array.push(i);
        let wrong = await db.collection('wrongNote').where({ //wrong.data[0].number:单词被错的次数
          user_id: wxContext.OPENID,
          word_id: i,
        }).get();
        if (wrong.data[0] == null)
          map.set(i, 0)
        else
          map.set(i, wrong.data[0].number);
      }
      const size = array.length;
      //排序
      for (let i = 0; i < size; i++) {
        for (let j = size - 1 - i; j > 0; j--) {
          if (map.get(array[j]) > map.get(array[j - 1])) {
            var temp = array[j - 1];
            array[j - 1] = array[j];
            array[j] = temp
          }
        }
      }
    } else { //背单词数大于设定值
      log = 2;
      //生成单词id队列
      for (let i = 0; i < event.num; i++) {
        while (true) {
          var random = parseInt((Math.random() * (word_id - 1) + 1).toFixed(0)); //return 1~word_id
          if (!array.includes(random)) {
            array.push(random);
            break;
          }
        }
      }
      const length = array.length;

      //获取背错次数
      for (let i = 0; i < length; i++) {
        let wrong = await db.collection('wrongNote').where({ //wrong.data[0].number:单词被错的次数
          user_id: wxContext.OPENID,
          word_id: array[i],
        }).get();
        if (wrong.data[0] == null)
          map.set(array[i], 0)
        else
          map.set(array[i], wrong.data[0].number);
      }

      //排序
      for (let i = 0; i < length; i++) {
        for (let j = length - 1 - i; j > 0; j--) {
          if (map.get(array[j]) > map.get(array[j - 1])) {
            var temp = array[j - 1];
            array[j - 1] = array[j];
            array[j] = temp
          }
        }
      }
    }

    //现在array为按照背错次数由大到小排好的数组
    for (let i = 0; i < array.length; i++) {
      let word = await db.collection('word').where({
        word_id: array[i],
      }).get();
      result.push(word.data[0]);
    }

    var mapValue = new Array();
    for (let i = 0; i < array.length; i++) {
      var string = "键：" + array[i] + " 值：" + map.get(array[i]);
      mapValue.push(string);
    }

    return {
      mapValue: mapValue,
      _log: log,
      words: result,
    }

  } catch (e) {
    console.error(e);
  }

}